import com.google.common.io.Files;
import com.google.googlejavaformat.java.Formatter;
import com.google.googlejavaformat.java.FormatterException;
import com.google.googlejavaformat.java.JavaFormatterOptions;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class Format {

    private static Formatter formatter;
    private static final Gson gson = new Gson();

    public static void main(String[] args) {
        var type = System.getenv("JIANMU_TYPE");
        var files = System.getenv("JIANMU_FILES");
        init(type);
        var filePathList = parseFiles(files);
        for (Object filePath : filePathList) {
            var file = new File(filePath.toString());
            if (!file.exists()) {
                System.out.println("error: 文件 " + filePath + " 不存在");
                System.out.println();
                continue;
            }
            recursionFile(file);
        }
    }

    public static void init(String type) {
        JavaFormatterOptions.Style style = null;
        try {
            style = JavaFormatterOptions.Style.valueOf(type);
        } catch (IllegalArgumentException e) {
            System.out.println("error: type错误，请输入正确的type (AOSP/GOOGLE)");
            System.exit(1);
        }
        var formatterOptions =
                JavaFormatterOptions.builder().style(style).formatJavadoc(true).build();
        formatter = new Formatter(formatterOptions);
    }

    public static List parseFiles(String files) {
        if (files == null || files.isBlank()) {
            System.out.println("error: 输入参数files不能为空");
        }
        try {
            var list = gson.fromJson(files, List.class);
            if (list.isEmpty()) {
                System.out.println("warn: files 是一个空集合");
            }
            return list;
        } catch (Exception e) {
            System.out.println("error: files解析失败：" + e);
            System.exit(1);
        }
        return null;
    }

    public static void recursionFile(File file) {
        if (file.isFile()) {
            formatFile(file);
            return;
        }
        var files = file.listFiles();
        for (File file1 : files) {
            recursionFile(file1);
        }
    }

    public static void formatFile(File file) {
        var charSource = Files.asCharSource(file, StandardCharsets.UTF_8);
        var charSink = Files.asCharSink(file, StandardCharsets.UTF_8);
        try {
            formatter.formatSource(charSource, charSink);
            System.out.println("success: file: " + file.getAbsolutePath() + "; 代码格式化成功");
            System.out.println();
        } catch (FormatterException | IOException e) {
            System.out.println("error: file: " + file.getAbsolutePath() + "; 代码格式化失败：\n  " + e);
            System.out.println();
        }
    }
}
